﻿using System;
using System.ComponentModel;
using System.Linq;

namespace Wonders.Core {
    public class CacheKeyManager<T> {

        private static string prekey = "";
        static CacheKeyManager() {
            prekey = typeof(T).Namespace.Replace(".", "_");
        }

        static string GetKeyStr(string key, T type) {
            string description = GetEnumDescription(type);
            return key;
        }

        public static string GetKey(T type, string value = "") {
            string key = string.Format("{0}_{1}", prekey, type.ToString());
            if (!string.IsNullOrEmpty(value)) key += "_" + value;
            return GetKeyStr(key, type);
        }

        public static string GetKey(T type, string AppId, string value) {
            string key = string.Format("{0}_AppId_{1}_{2}", prekey, AppId, type.ToString());
            if (!string.IsNullOrEmpty(value)) key += "_" + value;
            return GetKeyStr(key, type);
        }

        public static string GetUserKey(T type, string AppUId, string value)
        {
            string key = string.Format("{0}_AppUId_{1}_{2}", prekey, AppUId, type.ToString());
            if (!string.IsNullOrEmpty(value)) key += "_" + value;
            return GetKeyStr(key, type);
        }

        public static string GetKey(T type, string AppId, string AppUId, string value) {
            string key = string.Format("{0}_AppId_{1}_AppUId_{2}_{3}", prekey, AppId, AppUId, type.ToString());
            if (!string.IsNullOrEmpty(value)) key += "_" + value;
            return GetKeyStr(key, type);
        }

       

        static string GetEnumDescription(T value) {
            Type type = typeof(T);
            var name = Enum.GetNames(type).Where(f => f.Equals(value.ToString(), StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();

            if (name == null) {
                return string.Empty;
            }
            var field = type.GetField(name);
            var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
        }
    }

}
